import { Reducer } from 'redux';
import { Effect, Subscription } from 'dva';
import { IFoodProps } from '@/pages/order/components/sell'


export interface ICartProps extends IFoodProps {
    skuSpliceId: string;
    buy_numbers: number;
}

export interface IGlobalState {
    /** 基础运费 */
    basePostFree: number;
    /** 起送价 */
    minPrice: number;
    /** 购物车信息 */
    shoppingcars: Array<ICartProps>;
}

export interface IdvaProps {
    namespace: string;
    state: IGlobalState;
    effects?: Record<string, Effect | undefined>;
    reducers: Record<string, Reducer<any, { type: string, payload: any }>>;
    subscriptions: Record<string, Subscription>;
}

const globalState: IdvaProps = {
    namespace: 'globalState',
    state: {
        basePostFree: 0,
        minPrice: 0,
        shoppingcars: []
    },
    reducers: {
        /** 设置起步价 */
        setMinPrice(state: IGlobalState, { payload }) {
            return {
                ...state,
                minPrice: payload
            }
        },
        /** 设置运费 */
        setBasePostFree(state: IGlobalState, { payload }) {
            return {
                ...state,
                basePostFree: payload
            }
        },
        /** 添加某个规格集合商品到购物车 */
        addSkuFoodToCart(state: IGlobalState, { payload }: { type: string, payload: ICartProps }) {
            let { shoppingcars } = state;
            const haveInshoppingcars = shoppingcars.findIndex(item => item.skuSpliceId === payload.skuSpliceId);
            if (haveInshoppingcars !== -1) {
                shoppingcars[haveInshoppingcars].buy_numbers += payload.buy_numbers;
            } else {
                shoppingcars.push({ ...payload })
            }
            return {
                ...state,
                shoppingcars
            }
        },
        /** 删除某个规格集合商品到购物车 */
        delSkuFoodToCart(state: IGlobalState, { payload }: { type: string, payload: ICartProps }) {
            let { shoppingcars } = state;
            const haveInshoppingcars = shoppingcars.findIndex(item => item.skuSpliceId === payload.skuSpliceId);
            if (haveInshoppingcars !== -1) {
                shoppingcars[haveInshoppingcars].buy_numbers--;
                if (!shoppingcars[haveInshoppingcars].buy_numbers) {
                    shoppingcars.splice(haveInshoppingcars, 1)
                }
            }
            return {
                ...state,
                shoppingcars
            }
        },
        /** 清空购物车 */
        clearShoppingcar(state: IGlobalState) {
            state.shoppingcars.splice(0, state.shoppingcars.length)
            return { ...state }
        }
    },
    subscriptions: {}
}


export default globalState